//
// Created by Administrator on 2021/5/20.
//

#include <unistd.h>

#include "CMMsgTaskInterface.h"
#include "CMMsgTaskManager.h"

/**
 * 让你的功能类，继承这个接口，并实现 handler 函数
 */
class CMMsgTaskRunner1 : public CMMsgTaskInterface
{
  public:
    ~CMMsgTaskRunner1() override {}

    int handler(int cmd, char *args, void *data) override
    {
        printf("runner 1: cmd [%d], args [%s] data[ %p]\n", cmd, args, data);
        return 0;
    }
};

class CMMsgTaskRunner2 : public CMMsgTaskInterface
{
  public:
    ~CMMsgTaskRunner2() override {}

    int handler(int cmd, char *args, void *data) override
    {

        printf("runner 2: cmd [%d], args [%s] data[ %p]\n", cmd, args, data);
        if (data)
        {
            int *x = (int *)data;
            printf("x = [%d]\n", *x);
            delete x;
        }

        return 0;
    }
};

void test_task_manager()
{
    printf("Program start\n");
    // 如果要简单一点，可以将这个放在全局单例中
    // 一个类相当于一个消息通道
    CMMsgTaskManager taskManager;
    taskManager.Init();

    // 将你的功能函数注册进 taskManager，这样，有消息时会调用 handler 函数
    CMMsgTaskRunner1 runner1;
    CMMsgTaskRunner2 runner2;
    CMMsgTaskRunner2 runner3;
    // 同一个名字可以注册多个，都会收到
    taskManager.Register("runner1", &runner1);
    taskManager.Register("runner2", &runner2);
    taskManager.Register("runner1", &runner3);

    int c = 0;
    while (c++ < 15)
    {
        if (c == 2)
            taskManager.Send("runner1", 22, "test_runner1", NULL);
        if (c % 5 == 0)
        {
            int *x = new int;
            *x     = 5;
            taskManager.Send("runner2", 235, "test_runner2", x);
            taskManager.Send("runner2", 236, "test_runner22", NULL);
        }
        sleep(1);
    }
    // 清除所有注册的
    taskManager.Clear();
    printf("clear done, runner should not receiver\n");
    // 这时个发送就没有用
    taskManager.Send("runner2", 123, "test_no", NULL);
    sleep(2);
    taskManager.Deinit();
    printf("Done, exit\n");
}

int main()
{
    test_task_manager();
    getchar();
    return 0;
}